<template>
  <div>
    <!-- 页面标题和操作按钮 -->
    <div class="d-flex justify-space-between align-center mb-6">
      <h1 class="text-h4 font-weight-bold">班级管理</h1>
      <v-btn
        color="primary"
        prepend-icon="mdi-plus"
        @click="openClassDialog()"
        size="large"
      >
        添加班级
      </v-btn>
    </div>

    <!-- 筛选和搜索 -->
    <v-row class="mb-6">
      <v-col cols="12" md="3">
        <v-select
          v-model="selectedGrade"
          :items="gradeOptions"
          label="筛选年级"
          variant="filled"
          density="comfortable"
          clearable
          @update:model-value="loadClasses"
        ></v-select>
      </v-col>
      <v-col cols="12" md="9">
        <v-text-field
          v-model="searchText"
          prepend-inner-icon="mdi-magnify"
          label="搜索班级名称"
          variant="filled"
          density="comfortable"
          clearable
        ></v-text-field>
      </v-col>
    </v-row>

    <!-- 班级列表 -->
    <v-card>
      <v-card-text>
        <!-- 移动端完整视图 -->
        <div v-if="mobile" class="mobile-class-list">
          <v-card
            v-for="classItem in paginatedMobileClasses"
            :key="classItem.id"
            class="mb-3"
            variant="outlined"
          >
            <v-card-text class="pa-2">
              <!-- 头部信息：ID、班级名称、年级、学生人数 -->
              <div class="d-flex align-center mb-2">
                <v-avatar color="primary" size="32" class="me-2">
                  <span class="text-white text-caption">{{ classItem.grade.charAt(0) }}</span>
                </v-avatar>
                <div class="flex-grow-1">
                  <div class="d-flex align-center justify-space-between">
                    <div>
                      <div class="font-weight-medium text-body-2">{{ classItem.name }} <span class="text-caption text-medium-emphasis">(ID: {{ classItem.id }})</span></div>
                      <div class="text-caption text-medium-emphasis">{{ classItem.grade }}</div>
                    </div>
                    <v-chip :color="classItem.student_count > 0 ? 'primary' : 'grey'" size="x-small" variant="elevated">
                      <v-icon start size="12">mdi-account-group</v-icon>
                      {{ classItem.student_count }}
                    </v-chip>
                  </div>
                </div>
              </div>
              
              <!-- 教师信息：紧凑显示 -->
              <div class="mb-2">
                <div class="d-flex align-center gap-1">
                  <v-icon size="14" color="medium-emphasis">mdi-account-tie</v-icon>
                  <span class="text-caption text-medium-emphasis">教师:</span>
                  <div v-if="classItem.teachers" class="d-flex flex-wrap gap-1">
                    <v-chip
                      v-for="teacher in classItem.teachers.split(', ')"
                      :key="teacher"
                      size="x-small"
                      variant="outlined"
                    >
                      {{ teacher }}
                    </v-chip>
                  </div>
                  <span v-else class="text-caption text-medium-emphasis">未分配</span>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="d-flex justify-end gap-1">
                <v-btn
                  size="small"
                  variant="outlined"
                  color="primary"
                  icon="mdi-account-group"
                  @click="goToStudentManagement(classItem)"
                ></v-btn>
                <v-btn
                  size="small"
                  variant="outlined"
                  color="secondary"
                  icon="mdi-pencil"
                  @click="openClassDialog(classItem)"
                ></v-btn>
                <v-btn
                  size="small"
                  variant="outlined"
                  color="info"
                  icon="mdi-account-tie"
                  @click="openTeacherDialog(classItem)"
                ></v-btn>
                <v-btn
                  size="small"
                  variant="outlined"
                  color="error"
                  icon="mdi-delete"
                  @click="deleteClass(classItem)"
                  :disabled="classItem.student_count > 0"
                ></v-btn>
              </div>
            </v-card-text>
          </v-card>
          
          <!-- 移动端分页 -->
          <div class="d-flex justify-center mt-4">
            <v-pagination
              v-model="mobilePage"
              :length="mobilePageCount"
              :total-visible="5"
              size="small"
            ></v-pagination>
          </div>
        </div>

        <!-- 桌面端数据表格 -->
        <v-data-table
          v-else
          :headers="headers"
          :items="filteredClasses"
          :loading="loading"
          class="elevation-1"
          :items-per-page="10"
        >
          <template v-slot:item.name="{ item }">
            <div class="d-flex align-center">
              <v-avatar color="primary" size="32" class="me-3">
                <span class="text-white text-caption">{{ item.grade.charAt(0) }}</span>
              </v-avatar>
              <div>
                <div class="font-weight-medium">{{ item.name }}</div>
                <div class="text-caption text-medium-emphasis">{{ item.grade }}</div>
              </div>
            </div>
          </template>

          <template v-slot:item.teachers="{ item }">
            <div v-if="item.teachers">
              <v-chip
                v-for="teacher in item.teachers.split(', ')"
                :key="teacher"
                size="small"
                class="ma-1"
              >
                {{ teacher }}
              </v-chip>
            </div>
            <span v-else class="text-medium-emphasis">未分配</span>
          </template>

          <template v-slot:item.student_count="{ item }">
            <v-chip
              :color="item.student_count > 0 ? 'primary' : 'grey'"
              size="small"
              variant="elevated"
            >
              {{ item.student_count }} 人
            </v-chip>
          </template>

          <template v-slot:item.actions="{ item }">
            <v-tooltip text="管理学生">
              <template v-slot:activator="{ props }">
                <v-btn
                  icon
                  size="small"
                  variant="text"
                  color="primary"
                  v-bind="props"
                  @click="goToStudentManagement(item)"
                >
                  <v-icon>mdi-account-group</v-icon>
                </v-btn>
              </template>
            </v-tooltip>
            
            <v-tooltip text="编辑班级">
              <template v-slot:activator="{ props }">
                <v-btn
                  icon
                  size="small"
                  variant="text"
                  v-bind="props"
                  @click="openClassDialog(item)"
                >
                  <v-icon>mdi-pencil</v-icon>
                </v-btn>
              </template>
            </v-tooltip>
            
            <v-tooltip text="分配教师">
              <template v-slot:activator="{ props }">
                <v-btn
                  icon
                  size="small"
                  variant="text"
                  v-bind="props"
                  @click="openTeacherDialog(item)"
                >
                  <v-icon>mdi-account-tie</v-icon>
                </v-btn>
              </template>
            </v-tooltip>
            
            <v-tooltip text="删除班级">
              <template v-slot:activator="{ props }">
                <v-btn
                  icon
                  size="small"
                  variant="text"
                  color="error"
                  v-bind="props"
                  @click="deleteClass(item)"
                  :disabled="item.student_count > 0"
                >
                  <v-icon>mdi-delete</v-icon>
                </v-btn>
              </template>
            </v-tooltip>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 班级编辑对话框 -->
    <v-dialog v-model="classDialog" max-width="500">
      <v-card>
        <v-card-title>
          {{ editingClass?.id ? '编辑班级' : '添加班级' }}
        </v-card-title>
        
        <v-card-text>
          <v-form ref="classFormRef" @submit.prevent="saveClass">
            <v-text-field
              v-model="classForm.name"
              label="班级名称"
              variant="filled"
              density="comfortable"
              :rules="nameRules"
              required
            ></v-text-field>
            
            <v-select
              v-model="classForm.grade"
              :items="gradeOptions"
              label="年级"
              variant="filled"
              density="comfortable"
              :rules="gradeRules"
              required
            ></v-select>
            
            <v-textarea
              v-model="classForm.description"
              label="描述"
              variant="filled"
              rows="3"
              density="comfortable"
            ></v-textarea>
          </v-form>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="classDialog = false">取消</v-btn>
          <v-btn color="primary" @click="saveClass" :loading="saving">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 教师分配对话框 -->
    <v-dialog v-model="teacherDialog" max-width="600">
      <v-card>
        <v-card-title>
          为 {{ editingClass?.name }} 分配教师
        </v-card-title>
        
        <v-card-text>
          <v-autocomplete
            v-model="selectedTeachers"
            :items="teachers"
            item-title="name"
            item-value="id"
            label="选择教师"
            multiple
            chips
            variant="filled"
            density="comfortable"
          ></v-autocomplete>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="teacherDialog = false">取消</v-btn>
          <v-btn color="primary" @click="assignTeachers" :loading="assigning">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDisplay } from 'vuetify'
import api from '@/utils/api'

const router = useRouter()
const { mobile } = useDisplay()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const assigning = ref(false)
const classes = ref([])
const teachers = ref([])
const searchText = ref('')
const selectedGrade = ref('')
const classDialog = ref(false)
const teacherDialog = ref(false)
const editingClass = ref(null)
const selectedTeachers = ref([])
const mobilePage = ref(1)
const mobileItemsPerPage = ref(10)

const classForm = ref({
  name: '',
  grade: '',
  description: ''
})

const classFormRef = ref(null)

// 表格标题
const headers = [
  { title: 'ID', key: 'id', sortable: true },
  { title: '班级信息', key: 'name', sortable: true },
  { title: '教师', key: 'teachers', sortable: false },
  { title: '学生人数', key: 'student_count', sortable: true },
  { title: '操作', key: 'actions', sortable: false }
]

// 年级选项
const gradeOptions = [
  '小班', '中班', '大班', '学前班'
]

// 计算属性
const filteredClasses = computed(() => {
  let result = classes.value
  
  if (selectedGrade.value) {
    result = result.filter(cls => cls.grade === selectedGrade.value)
  }
  
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    result = result.filter(cls => 
      cls.name.toLowerCase().includes(search)
    )
  }
  
  return result
})

const mobilePageCount = computed(() => {
  return Math.ceil(filteredClasses.value.length / mobileItemsPerPage.value)
})

const paginatedMobileClasses = computed(() => {
  const start = (mobilePage.value - 1) * mobileItemsPerPage.value
  const end = start + mobileItemsPerPage.value
  return filteredClasses.value.slice(start, end)
})

// 验证规则
const nameRules = [
  v => !!v || '班级名称不能为空',
  v => v.length >= 2 || '班级名称至少2个字符'
]

const gradeRules = [
  v => !!v || '请选择年级'
]

// 方法
const loadClasses = async () => {
  loading.value = true
  try {
    const response = await api.get('/classes')
    classes.value = response.data.data.classes
  } catch (error) {
    console.error('加载班级列表失败:', error)
    window.showNotification?.('加载班级列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const loadTeachers = async () => {
  try {
    const response = await api.get('/users/teachers')
    teachers.value = response.data.data
  } catch (error) {
    console.error('加载教师列表失败:', error)
  }
}

const openClassDialog = (classItem = null) => {
  editingClass.value = classItem
  if (classItem) {
    Object.assign(classForm.value, {
      name: classItem.name,
      grade: classItem.grade,
      description: classItem.description || ''
    })
  } else {
    Object.assign(classForm.value, {
      name: '',
      grade: '',
      description: ''
    })
  }
  classDialog.value = true
}

const saveClass = async () => {
  const { valid } = await classFormRef.value.validate()
  if (!valid) return
  
  saving.value = true
  try {
    if (editingClass.value?.id) {
      // 更新班级
      await api.put(`/classes/${editingClass.value.id}`, classForm.value)
      window.showNotification?.('班级信息更新成功', 'success')
    } else {
      // 创建班级
      await api.post('/classes', classForm.value)
      window.showNotification?.('班级创建成功', 'success')
    }
    
    classDialog.value = false
    loadClasses()
    
  } catch (error) {
    console.error('保存班级失败:', error)
    window.showNotification?.('保存班级失败', 'error')
  } finally {
    saving.value = false
  }
}

const openTeacherDialog = (classItem) => {
  editingClass.value = classItem
  // 解析已分配的教师
  const currentTeachers = classItem.teachers ? 
    classItem.teachers.split(', ').map(name => {
      const teacher = teachers.value.find(t => t.name === name)
      return teacher?.id
    }).filter(Boolean) : []
  
  selectedTeachers.value = currentTeachers
  teacherDialog.value = true
}

const assignTeachers = async () => {
  assigning.value = true
  try {
    await api.post(`/classes/${editingClass.value.id}/teachers`, {
      teacherIds: selectedTeachers.value
    })
    
    teacherDialog.value = false
    loadClasses()
    window.showNotification?.('教师分配成功', 'success')
    
  } catch (error) {
    console.error('分配教师失败:', error)
    window.showNotification?.('分配教师失败', 'error')
  } finally {
    assigning.value = false
  }
}

const goToStudentManagement = (classItem) => {
  router.push(`/admin/students?classId=${classItem.id}&className=${encodeURIComponent(classItem.name)}`)
}



const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const deleteClass = async (classItem) => {
  if (!confirm(`确定要删除班级 "${classItem.name}" 吗？`)) return
  
  try {
    await api.delete(`/classes/${classItem.id}`)
    loadClasses()
    window.showNotification?.('班级删除成功', 'success')
  } catch (error) {
    console.error('删除班级失败:', error)
    window.showNotification?.('删除班级失败', 'error')
  }
}

// 生命周期
onMounted(() => {
  loadClasses()
  loadTeachers()
})
</script>

<style scoped>
.v-data-table {
  border-radius: 8px;
}

.v-chip {
  font-size: 0.75rem;
}
</style>
